package ru.spbau.bytecode.projectobserver;

import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import ru.spbau.bytecode.graph.CompositeVertex;
import ru.spbau.bytecode.graph.Edge;
import ru.spbau.bytecode.graph.Graph;
import ru.spbau.bytecode.reader.BytecodeReader;

public class PackagesObserver extends ProjectObserver {
	
	@Override
	public String getName() {
		return "Packages";
	}

	@Override
	protected void findDependencies(File[] classFiles,
			File projectDirectory, Graph graph, File currentDirectory) throws IOException {
		Set<String> set = new HashSet<String>();
		Set<String> packages = new HashSet<String>();
		
		String currentDirectoryPath = currentDirectory.getAbsolutePath();

		String currentPackage = currentDirectoryPath.substring(
				projectDirectory.getAbsolutePath().length() + 1,
				currentDirectoryPath.length()).replace(File.separatorChar, '.');
		String[] currentPackageParts = currentPackage.split("[.]");
		CompositeVertex v1 = new CompositeVertex(currentPackage);
		graph.addVertex(v1);

		for (File f : classFiles) {
			BytecodeReader reader = new BytecodeReader();
			reader.run(f.getAbsolutePath());
			set.addAll(reader.getClasses());
		}

		for (String pack : set) {
			String[] parts = pack.split("[.]");
			
			if (parts.length < 4 ||
					!parts[0].equals(currentPackageParts[0]) ||
					!parts[1].equals(currentPackageParts[1]) ||
					!parts[2].equals(currentPackageParts[2])) {
				continue;
			}
			
			int lastDotOccur = pack.lastIndexOf('.');
			if (lastDotOccur == -1) {
				pack = "default package";
			} else {
				pack = pack.substring(0, lastDotOccur);
			}
			
			if (!pack.equals(currentPackage)) {
				packages.add(pack);
			}
		}

		for (String pack : packages) {
			CompositeVertex v2 = new CompositeVertex(pack);
			graph.addVertex(v2);
			graph.addEdge(new Edge(v1, v2));
		}
	}
}
